// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  openid = wxContext.OPENID
  let num = 5 //获取数量限制5
  let myself = await db.collection("users").where({_openid:openid}).get()
  let data = []
  if (myself.data.length == 0) {
    let fe = await db.collection("users").limit(num).get()
    data = data.concat(fe.data)
    return data
  }
  if (!myself.data[0].isComplete){
    if (data.length < num) {
      let se = await db.collection("users").where({
        province: myself.data[0].province,
        // school: _.not(_.eq(myself.data[0].school)),
        _openid: _.not(_.eq(myself.data[0]._openid))
      }).limit(num - data.length).get()
      data = data.concat(se.data)
    }
    if (data.length < num) {
      let ce = await db.collection("users").where({
        province: _.not(_.eq(myself.data[0].province)),
        // school: _.not(_.eq(myself.data[0].school)),
        _openid: _.not(_.eq(myself.data[0]._openid))
      }).limit(num - data.length).get()
      data = data.concat(ce.data)
    }
  }else{
    if (data.length < num) {
      let fe = await db.collection("users").where({
          school: myself.data[0].school,
        _openid: _.not(_.eq(myself.data[0]._openid))
      }).limit(num - data.length).get()
      data = data.concat(fe.data)
    }
    if (data.length < num) {
      let se = await db.collection("users").where({
        province: myself.data[0].province,
        school: _.not(_.eq(myself.data[0].school)),
        _openid: _.not(_.eq(myself.data[0]._openid))
      }).limit(num - data.length).get()
      data = data.concat(se.data)
    }
    if (data.length < num) {
      let ce = await db.collection("users").where({
        province: _.not(_.eq(myself.data[0].province)),
        school: _.not(_.eq(myself.data[0].school)),
        _openid: _.not(_.eq(myself.data[0]._openid))
      }).limit(num - data.length).get()
      data = data.concat(ce.data)
    }
  }
  // data = await db.collection("users").where({
  //   province: myself.data[0].province,
  //   _openid: _.not(_.eq(myself.data[0]._openid))
  // }).limit(num).get()
  return data
 
  // console.log(mysqlf)
  

}